export default {
	//开启命名空间
	namespaced: true,

	//数据节点
	state: () => ({
		//购物车数据
		cartDataList: [],
		cartAllNum: 0,
		cartAllPrice: 0

	}),
	//相当于异步操作，不能直接改变state的值，可以通过触发mutations来改变
	actions: {
		//1，设置msgData的值
		addCartData(stateData, addCartData) {
			//获取所有数据
			var cartData = stateData.state.cartDataList
			//判断是否有id一致的
			for (var i = 0; i < cartData.length; i++) {
				if (cartData[i].shopId == addCartData.shopId) {
					cartData[i].num = cartData[i].num + 1
					cartData[i].allPrice = cartData[i].allPrice + addCartData.allPrice

					stateData.commit('calculationAllPrice', addCartData.price)
					stateData.commit('addMutCartData', cartData)
					return
				}
			}
			cartData.push(addCartData)
			stateData.commit('calculationAllPrice', addCartData.price)
			stateData.commit('addMutCartData', cartData)
		},
		//2，减少msgData的值（-1）
		reduceCartDataOne(stateData, reduceCartData) {
			//获取所有数据
			var cartData = stateData.state.cartDataList
			//找到相同id数据
			for (var i = 0; i < cartData.length; i++) {
				if (cartData[i].shopId == reduceCartData.shopId) {
					//如果是最后一件商品（直接删除即可）
					if (cartData[i].num == 1) {
						cartData.splice(i, 1)
					} else {
						//商品数量减一
						cartData[i].num = cartData[i].num - 1
						//商品总价格减少
						cartData[i].allPrice = cartData[i].allPrice - reduceCartData.price
					}
					stateData.commit('calculationAllPrice', -reduceCartData.price)
					stateData.commit('reduceMutCartData', cartData)
					return
				}
			}
		},
		cleanCartData(stateData) {
			stateData.commit('cleanMutCartData')
		}

	},

	//方法节点（相当于同步操作）
	mutations: {
		//1，计算总价格
		calculationAllPrice(state, price) {
			state.cartAllPrice = state.cartAllPrice + price
		},
		addMutCartData(state, cartData) {
			state.cartDataList = cartData
			state.cartAllNum = state.cartAllNum + 1

			// var allPriceData = 0
			// for (var i = 0; i < cartData.length; i++) {
			// 	allPriceData += cartData[i].allPrice
			// }
			// state.cartAllPrice = allPriceData
			//保存到本地
			// uni.setStorageSync('cartDataList', cartData)
			// uni.setStorageSync('cartAllNum', state.cartAllNum)
		},
		reduceMutCartData(state, cartData) {
			state.cartDataList = cartData
			state.cartAllNum = state.cartAllNum - 1

			// var allPriceData = 0
			// for (var i = 0; i < cartData.length; i++) {
			// 	allPriceData += cartData[i].allPrice
			// }
			// state.cartAllPrice = allPriceData
		},
		cleanMutCartData(state, cartData) {
			state.cartDataList = []
		}

	},

	getters: {
		// getMsgList(state) {
		// 	return state.msgData
		// }
	}
}
